package cn.mw.cmdb.param;

import cn.mw.cmdb.entity.PropertyTypeExtMultiple;

import java.util.Comparator;
import java.util.Map;

import static cn.mw.cmdb.entity.InstanceInfo.SearchPrefix;
import static cn.mw.cmdb.entity.PropertyType.relationIdKey;
import static cn.mw.cmdb.entity.PropertyType.relationNameKey;

public interface MwRelationPropertyType {
    public static final String relationModelIdKey = "relationModelId";
    public static final String relationPropertyIdKey = "relationPropertyId";
    public static final String linkPropertyIdKey = "linkPropertyId";
    public static final String linkTargetPropertyIdKey = "linkTargetPropertyId";

    Map<String, Object> getRelationFieldId(String k, Object val, String instanceId, String replace);

    Object getRelationName(String k, Object val, String instanceId);

    static String getRelationIdPath(String name) {
        String path = SearchPrefix + "." + name + "." + relationIdKey;
        return path;
    }

    static String getRelationPropertyIdPath(String name) {
        String path = SearchPrefix + "." + name + "." + relationPropertyIdKey;
        return path;
    }

    static String getRelationNamePath(String name, String propertyTypeId) {
        String path = "";
        String queryName = "";
        if (name != null && name.indexOf(SearchPrefix) != -1) {
            queryName = name;
        } else {
            queryName = SearchPrefix + "." + name;
        }
        if (PropertyTypeExtMultiple.ID.equals(propertyTypeId)) {
            path = queryName + "." + "$[]" + "." + relationNameKey;
        } else {
            path = queryName + "." + relationNameKey;
        }
        return path;
    }

    static String updateRelationValPath(String name) {
        String path = SearchPrefix + "." + name;
        return path;
    }

    public class CustomKeyComparator implements Comparator<String> {
        private final Map<String, ?> map;

        public CustomKeyComparator(Map<String, ?> map) {
            this.map = map;
        }

        @Override
        public int compare(String key1, String key2) {
            // 自定义排序规则
            if (key1.equals(relationPropertyIdKey)) return -1;
            if (key2.equals(relationPropertyIdKey)) return 1;
            if (key1.equals(relationIdKey)) return -1;
            if (key2.equals(relationIdKey)) return 1;
            if (key1.equals(relationNameKey)) return -1;
            if (key2.equals(relationNameKey)) return 1;
            return key1.compareTo(key2); // 其他键按字母顺序排序
        }
    }
}
